import { ElMessage } from 'element-plus'

export const phoneRegex = (phone) => {
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    ElMessage({ type: 'info', message: '请输入正确的手机号', duration: 1000 })
    throw new Error('请输入正确的手机号')
  }
}

export const passwordRegex = (password) => {
  if (!/^[a-zA-Z0-9]{6,8}$/.test(password)) {
    ElMessage({ type: 'info', message: '请输入正确的密码', duration: 1000 })
    throw new Error('请输入正确的密码')
  }
}

export const codeRegex = (code) => {
  if (!/^\d{4}$/.test(code)) {
    ElMessage({ type: 'info', message: '请输入正确的验证码', duration: 1000 })
    throw new Error('请输入正确的验证码')
  }
}

export const imageRegex = ({ imageName, imageSize }) => {
  if (!/\.(jpg|png|jpeg|webp)$/i.test(imageName)) {
    ElMessage({ type: 'info', message: '请上传正确的图片文件格式(.jpg|.png|.jpeg|.webp)', duration: 1000 })
    throw new Error('请上传正确的图片文件格式(.jpg|.png|.jpeg|.webp)')
  }
  if (imageSize > 3 * 1024 * 1024) {
    ElMessage({ type: 'info', message: '请上传≤3MB的图片文件', duration: 1000 })
    throw new Error('请上传≤5MB的图片文件')
  }
}

export const emptyRegex = ({ value, msg }) => {
  if (typeof value === 'string' && value === '') {
    ElMessage({ type: 'info', message: msg, duration: 1000 })
    throw new Error('字符串非空校验')
  }
}

export const slideCaptcha = () => {
  return new Promise((resolve, reject) => {
    try {
      const captcha = new TencentCaptcha(import.meta.env.VITE_CAPTCHA_APPID, (res) => {
        if (res.errorMessage) {
          ElMessage({ type: 'info', message: res.errorMessage, duration: 1000 })
          reject(new Error(`errorCode: ${res.errorCode}, errorMessage: ${res.errorMessage}`))
        }
        else {
          if (res.ret !== 0) {
            ElMessage({ type: 'info', message: '用户主动关闭验证码', duration: 1000 })
            reject(new Error('用户主动关闭验证码'))
          }
          else {
            resolve({
              ticket: res.ticket,
              appid: res.appid,
              randstr: res.randstr
            })
          }
        }
      })
      captcha.show()
    }
    catch (err) {
      reject(err)
    }
  })
}

export const countdown = (countdownText, seconds) => {
  countdownText.value = `${seconds}s后重新获取`
  let timer = seconds
  const interval = setInterval(() => {
    if (timer <= 1) {
      clearInterval(interval)
      countdownText.value = '发送验证码'
    }
    else {
      timer = timer - 1
      countdownText.value = `${timer}s后重新获取`
    }
  }, 1000)
}